package com.x9space.framework.elastic.handler;

import com.x9space.common.utils.StringUtils;
import com.x9space.framework.elastic.annotation.TermMatch;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.Map;

public class TermMatchQueryHandler extends QueryHandler{
    @Override
    public String getName() {
        return "TermMatch";
    }

    @Override
    protected QueryBuilder _doHandle(Annotation annotation, Map<String, Object> context) {
        if (!(annotation instanceof TermMatch)) {
            return null;
        }
        TermMatch item = (TermMatch) annotation;


        String field = item.field();
        if (StringUtils.isEmpty(field)){
            field = ((Field)context.get("field")).getName();
        }

        TermQueryBuilder value = QueryBuilders.termQuery(field, context.get("value"));

        if (item.boost()>=0){
            value.boost(item.boost());
        }
        return value;
    }
}
